/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Server;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Calendar;

import Client.ClientUtils;
import Client.Client_Dashboard;
import Client.Main;

/**
 * 
 * @author TienNT
 */

public class Server extends Thread {
	private static final long serialVersionUID = 1L;

	Socket mSocket;
	DataInputStream mFromClient;
	DataOutputStream mToClient;

	public Server(Socket socket) {
		mSocket = socket;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub

		try {
			System.out.println("Server " + Main.count++ + " start...");
			mFromClient = new DataInputStream(mSocket.getInputStream());
			mToClient = new DataOutputStream(mSocket.getOutputStream());

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		while (true) {
			try { // Poll every ~10 ms
				Thread.sleep(10);
			} catch (InterruptedException e) {
			}

			try {
				final String s = mFromClient.readUTF();

				if (s.charAt(0) == '1') {
					// Login request
					String[] strings = s.split(":");

					String username = strings[1];
					String password = strings[2];

					// Truy xuat CSDL de dang nhap.
					// ....

					System.out.println(username + " has loged in");
					Main.getContactList().add(username);
					Main.getSocketList().add(mSocket);
					FileOutputStream fileOutputStream = new FileOutputStream(
							new File("F:/temp"));
					PrintWriter printWriter = new PrintWriter(fileOutputStream);
					int i = Main.getContactList().size();
					printWriter.println(i);
					for (int j = 0; j < i; j++) {
						printWriter.println(Main.getContactList().get(j));
					}
					printWriter.flush();
					printWriter.close();
					fileOutputStream.close();

					mToClient.writeInt(ClientUtils.ACCEPT);
					int x = Main.getContactList().size();
					System.out.println(x);
					for (i = 0; i < x; i++) {
						Socket socket = (Socket) Main.getSocketList().get(i);
						if (socket != mSocket) {
							DataOutputStream out = new DataOutputStream(
									socket.getOutputStream());
							out.writeInt(ClientUtils.CONTACT_LIST_CHANGED);
						}
					}

					mToClient.flush();
				}
			} catch (IOException ex) {

			} /*
			 * catch (InterruptedException e) { // TODO Auto-generated catch
			 * block e.printStackTrace(); }
			 */
		}
	}

}
